package cc.eddic.examinationsystem.webapi;

import cc.eddic.examinationsystem.domain.*;
import cc.eddic.examinationsystem.dto.AnswerAddRequest;
import cc.eddic.examinationsystem.repository.*;

import lombok.extern.slf4j.Slf4j;

import lombok.val;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.transaction.Transactional;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@RestController
@RequestMapping("/api/answer")
public class AnswerRestController {

    public AnswerRestController(ExamRepository examRepository, AnswerRepository answerRepository, StudentRepository studentRepository, QuestionRepository questionRepository, ExamScoreRepository examScoreRepository) {
        this.examRepository = examRepository;
        this.answerRepository = answerRepository;
        this.studentRepository = studentRepository;
        this.questionRepository = questionRepository;
        this.examScoreRepository = examScoreRepository;
    }

    @Transactional
    @PostMapping("/save-answer")
    public ResponseEntity<Map<String, Object>> save(@RequestBody List<AnswerAddRequest> answerAddRequest){
        log.debug("answer add request size {}", answerAddRequest.size());

        val oo = answerAddRequest.stream().findFirst().get();
        Exam exam = examRepository.findById(oo.getExamId())
                .orElseThrow(NoSuchElementException::new);
        Student student = studentRepository.findById(oo.getStudentId())
                .orElseThrow(NoSuchElementException::new);

        AtomicInteger totalScore = new AtomicInteger(0);
        Integer scoreByQuestion = exam.getTotalScore() / answerAddRequest.size();

        answerAddRequest.stream().forEach(req -> {
            log.debug("{}",req);
            Question question = questionRepository.findById(req.getQuestionId())
                    .orElseThrow(NoSuchElementException::new);

            log.debug("{} {} {}",question,exam,student);
            Answer answer = Answer.builder()
                    .question(question)
                    .exam(exam)
                    .student(student)
                    .choice(req.getChoice())
                    .build();

            int questionScore = 0;
            if (req.getChoice() != null) {
                questionScore = calculateScore(question, req.getChoice());
            }
            int adjustedQuestionScore = questionScore * scoreByQuestion;
            totalScore.addAndGet(adjustedQuestionScore);

            question.add(answer);
            exam.add(answer);
            student.add(answer);
            answerRepository.save(answer);
        });

        Integer finalTotalScore = totalScore.get();
        ExamScore examScore=ExamScore.builder()
               .exam(exam)
               .student(student)
               .score(finalTotalScore)
               .build();
        examScoreRepository.save(examScore);

        Map<String, Object> response = new HashMap<>();
        response.put("message", "Answers saved successfully");
        return ResponseEntity.ok().body(response);
    }
    private int calculateScore(Question question, Character choice) {
        for (Option option : question.getOptions()) {
            if (option.isCorrect() && choice == option.getChoice()) {
                return 1;
            }
        }
        return 0;
    }

    private final ExamRepository examRepository;

    private final AnswerRepository answerRepository;

    private final StudentRepository studentRepository;

    private final QuestionRepository questionRepository;

    private final ExamScoreRepository examScoreRepository;
}
